package learnonline.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import learnonline.dao.TeacherDao;
import learnonline.dao.impl.TeacherDaoImpl;
import learnonline.entity.Teacher;

@WebServlet("/userinformationupdate")
public class UserInformationUpdate extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		TeacherDao teacherdao = new TeacherDaoImpl();
		int tid = 0;
		// int tid = Integer.valueOf(req.getParameter("tid"));
		System.out.println(tid);
		String timage = "";
		String tname = null;
		String tdescription = null;
		String virtualPath = null;
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> items = upload.parseRequest(req);
			for (FileItem item : items) {
				if (item.isFormField()) {
					if("tname".equals(item.getFieldName())){
						tname = item.getString("UTF-8");
						
					}else if("tdescription".equals(item.getFieldName())){
						tdescription = item.getString("UTF-8");
						
					}else if("tid".equals(item.getFieldName())){
						tid = Integer.valueOf(item.getString("UTF-8"));
						
					}
				}else{
						String clientFilename = item.getName();
						System.out.println(clientFilename);
					if (!clientFilename.isEmpty()) {
						String ext = clientFilename.substring(clientFilename.lastIndexOf("."));
						timage = System.currentTimeMillis() + ext;
						 virtualPath = "/images/" + timage;
						String path = req.getServletContext().getRealPath(virtualPath);
						File file = new File(path);
						item.write(file);
					}
				}
				}

			

		} catch (Exception e) {
			throw new RuntimeException("上传文件时发生错误！", e);
		}

		teacherdao.updateTeacher(tid, tname, tdescription, timage);
		resp.sendRedirect("teachermanage");
	}
}